
/**
 * AppleIIGo
 * Paddles class
 * (C) 2007-2008 by Marc S. Ressl (mressl@umich.edu)
 * Released under the GPL
 */

#include "Paddles.h"

Paddles::Paddles(Motherboard * motherboard) :
	Device(motherboard, "Paddles") {
	initButton(0);
	initButton(1);
	initButton(2);
	setPosition(0, PADDLEPOSITION_CENTER);
	setPosition(1, PADDLEPOSITION_CENTER);
	setPosition(2, PADDLEPOSITION_CENTER);
	setPosition(3, PADDLEPOSITION_CENTER);
}

void Paddles::onDevicesConnected() {
	timingGenerator = motherboard->getTimingGenerator();
}

void Paddles::onResetAsserted(bool isRestart) {
	annunciatorRegister = 0;
	resetTimer();
}

void Paddles::setAnnunciator(UINT32 index, bool value) {
	setBit(annunciatorRegister, (1 << index), value);
}

bool Paddles::getAnnunciator(UINT32 index) {
	return getBit(annunciatorRegister, (1 << index));
}

void Paddles::initButton(UINT32 index) {
	if (index < PADDLEBUTTON_NUM)
		buttonCount[index] = 0;
}

void Paddles::pushButton(UINT32 index) {
	if (index < PADDLEBUTTON_NUM)
		buttonCount[index]++;
}

void Paddles::pullButton(UINT32 index) {
	if (index < PADDLEBUTTON_NUM)
		buttonCount[index]--;
}

bool Paddles::isButtonDown(UINT32 index) {
	if (index < PADDLEBUTTON_NUM)
		return buttonCount[index];
	
	return false;
}

void Paddles::setPosition(UINT32 index, UINT32 value) {
	// Applesoft ROM, $FB1E - $FB2E
	if (index < PADDLEAXIS_NUM)
		timerLength[index] = (value * 11 + 8) * CLOCK14M_CYCLESHORT;
}

void Paddles::resetTimer() {
	timingGenerator->assertDisableCpuAccelerationForOneFrame();
	timerIndex[0] = timingGenerator->getClockIndex() + timerLength[0];
	timerIndex[1] = timingGenerator->getClockIndex() + timerLength[1];
	timerIndex[2] = timingGenerator->getClockIndex() + timerLength[2];
	timerIndex[3] = timingGenerator->getClockIndex() + timerLength[3];
}

bool Paddles::isTimedOut(UINT32 index) {
	if (index < PADDLEAXIS_NUM)
		return (timerIndex[index] > timingGenerator->getClockIndex()); 
	
	return false;
}
